using UnityEngine;
using System.Collections;

public class SantaClaus : MonoBehaviour
{
    public float gravity;
    public float speed = 0;
    public Transform gift;
    private float chronometer;
    private bool pressed = false;
    private bool invencible = false;
    public Texture2D[] textures;

    void Update()
    {
        Touch[] touches = Input.touches;

        transform.Translate(0, 0, speed * Time.deltaTime);

        chronometer += Time.deltaTime;

        if(touches.Length == 0)
        {
            pressed = false;
        }

        if(pressed == false || transform.position.y > 6.5)
        {
            if(speed > -2.7)
            {
                speed -= gravity;
            }
        }

        if(transform.position.y < -5)
        {
            speed += gravity * 2;
        }

        foreach(Touch touch in touches)
        {
            if(touch.position.x > Screen.width / 2 && transform.position.y <= 6.5)
            {
                if(speed < 2.7)
                {
                    speed += gravity;
                }

                pressed = true;

                if(touch.phase == TouchPhase.Ended)
                {
                    pressed = false;
                }
            }

            if(touch.position.x < Screen.width / 2)
            {
                if(touch.phase == TouchPhase.Began && chronometer > 0.5 && IsInvencible() == false)
                {
                    Instantiate(gift, new Vector3(transform.position.x - 1, transform.position.y, transform.position.z), transform.rotation);
                    StartCoroutine("Animate");
                    chronometer = 0;
                }
            }
        }
    }

    private IEnumerator Animate()
    {
        renderer.material.mainTexture = textures[1];

        yield return new WaitForSeconds(0.5f);

        renderer.material.mainTexture = textures[0];
    }

    public void Die()
    {
        PlayerInformations.RemoveLife();

        speed = 0;

        if(PlayerInformations.Life >= 0)
        {
            transform.position = new Vector3(-6.5f, 6.5f, -3.5f);
        }

        StartCoroutine("MakeInvincible");
    }

    public IEnumerator MakeInvincible()
    {
        invencible = true;
        renderer.material.color = new Color32(255, 90, 90, 255);

        yield return new WaitForSeconds(2);

        invencible = false;
        renderer.material.color = Color.white;
    }

    public bool IsInvencible() { return invencible; }
}